﻿#region Using Directives

using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections.Generic;

using QuickDev.Common;
using QuickDev.Common.Audit;
using QuickDev.Localization;

using QuickDev.Web.App;
using QuickDev.Web.UI;

using QuickDev.Model;
using QuickDev.Caching;
using QuickDev.BLL;
using QuickDev.Web.App.controls;
using QuickDev.Common.Serialization;

#endregion

namespace QuickDev.Web.App.Administration
{
    public partial class ReturnOrderAdd : AdminPage
    {
        #region Page Events

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load( object sender , EventArgs e )
        {
            try
            {
                SetProperties();

                DisplayLines();

                if ( !Page.IsPostBack )
                {
                   
                }
            }
            catch ( Exception ex )
            {
                Logger.Error( typeof( ReturnOrderAdd ).Name + ".Page_Load" , ex );
                Master.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click( object sender , EventArgs e )
        {
            if ( Page.IsValid )
            {
                try
                {
                    string wangwangId = txtWangWangId.Text.Trim();
                    string customerName = txtName.Text.Trim();
                    string customerCellPhone = txtCustomerCellPhoneNumber.Text.Trim();
                    string customerAddress = txtCustomerAddress.Text.Trim();

                    ReturnOrderHeader model = ReturnOrderHeaderBLL.Insert( wangwangId , customerName , customerCellPhone , customerAddress , Memberships.CurrentUserId );

                    bool flag = false;

                    if ( model != null && model.Id > 0 )
                    {
                        #region ReturnOrderDetail

                        flag = true;
                        foreach ( ucPickLine line in plhLines.Controls )
                        {
                            string productNumber = String.Empty;
                            TextBox txtProductNumber = line.FindControl( "txtProductNumber" ) as TextBox;
                            if ( txtProductNumber != null )
                            {
                                productNumber = txtProductNumber.Text.Trim();
                            }

                            if ( !String.IsNullOrEmpty( productNumber ) )
                            {
                                int qty = 0;
                                DropDownList ddlQty = line.FindControl( "ddlQty" ) as DropDownList;
                                if ( ddlQty != null )
                                {
                                    int.TryParse( ddlQty.SelectedValue , out qty );
                                }

                                int returnTypeId = 0;
                                DropDownList ddlReturnTypes = line.FindControl( "ddlReturnTypes" ) as DropDownList;
                                if ( ddlReturnTypes != null )
                                {
                                    int.TryParse( ddlReturnTypes.SelectedValue , out returnTypeId );
                                }

                                string xml = String.Empty;
                                CheckBoxList cblReturnReasons = line.FindControl( "cblReturnReasons" ) as CheckBoxList;
                                if ( cblReturnReasons != null )
                                {
                                    List<ReturnReason> list = new List<ReturnReason>();
                                    foreach ( ListItem item in cblReturnReasons.Items )
                                    {
                                        if ( item.Selected )
                                        {
                                            list.Add( ReturnReasonCache.GetModel( int.Parse( item.Value ) ) );
                                        }
                                    }
                                    Serializer serializer = new Serializer();
                                    xml = serializer.SerializeObject( list , typeof( List<ReturnReason> ) );
                                }

                                bool otherReasonChecked = false;
                                CheckBox cbOtherReasonChecked = line.FindControl( "cbOtherReasonChecked" ) as CheckBox;
                                if ( cbOtherReasonChecked != null )
                                {
                                    otherReasonChecked = cbOtherReasonChecked.Checked;
                                }

                                string otherReasonContent = String.Empty;
                                TextBox txtOtherReasonContent = line.FindControl( "txtOtherReasonContent" ) as TextBox;
                                if ( txtOtherReasonContent != null )
                                {
                                    otherReasonContent = txtOtherReasonContent.Text.Trim();
                                }

                                ReturnOrderDetail rod = ReturnOrderDetailBLL.Insert( model.Id , productNumber , qty , returnTypeId , xml , otherReasonChecked , otherReasonContent , Memberships.CurrentUserId );
                                flag &= ( rod != null ) && ( rod.Id > 0 );
                            }
                        }

                        #endregion
                    }

                    if ( flag )
                    {
                        Response.Redirect( String.Format( "ReturnOrderEdit.aspx?orderId={0}" , model.Id ) );
                    }
                    else
                    {
                        Master.MessageCenter.DisplayFailureMessage( string.Format( LocalizationUtility.GetText( "lblNotSaved" ) , typeof( ReturnOrderHeader ).Name ) );
                    }
                }
                catch ( System.Threading.ThreadAbortException )
                {
                    //ignore error.
                }
                catch ( Exception ex )
                {
                    Logger.Error( typeof( ReturnOrderAdd ).Name + ".btnSave_Click" , ex );
                    Master.MessageCenter.DisplayCriticalMessage( ex.Message );
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the btnReset control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void btnReset_Click( object sender , EventArgs e )
        {
            Response.Redirect( HttpContext.Current.Request.Url.ToString() );
        }


        /// <summary>
        ///This method is called when a user clicks the Add Line button.
        /// </summary>
        /// <param name="s">The s.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnAddLineClick( Object s , EventArgs e )
        {
            try
            {
                LineCount++;
                AddLine( true );
                btnRemoveLine.Enabled = true;
            }
            catch ( Exception ex )
            {
                Logger.Error( typeof( ReturnOrderAdd ).Name + ".btnAddLineClick" , ex );
                Master.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        /// <summary>
        /// This method is called when a user clicks the Remove Line button.
        /// </summary>
        /// <param name="s">The s.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnRemoveLineClick( Object s , EventArgs e )
        {
            try
            {
                if ( LineCount > 1 )
                {
                    LineCount--;
                    plhLines.Controls.RemoveAt( plhLines.Controls.Count - 1 );
                }

                if ( LineCount < 2 )
                    btnRemoveLine.Enabled = false;
            }
            catch ( Exception ex )
            {
                Logger.Error( typeof( ReturnOrderAdd ).Name + ".btnRemoveLineClick" , ex );
                Master.MessageCenter.DisplayCriticalMessage( ex.Message );
            }
        }

        #endregion

        #region Methods

        #region Private

        /// <summary>
        /// Sets the ReturnOrderHeaders properties.
        /// </summary>
        private void SetProperties()
        {
            this.Title = string.Format( WebUtility.MainTitleTemplate , Master.SiteSettings.SiteName , "新增退换单" );
        }

        /// <summary>
        /// This method adds the number of clauses stored in the LineCount property.
        /// </summary>
        void DisplayLines()
        {
            for ( int i=0 ; i < LineCount ; i++ )
                AddLine( false );
        }

        /// <summary>
        /// This method adds a new query clause to the user interface.
        /// </summary>
        /// <param name="bindData">if set to <c>true</c> [bind data].</param>
        void AddLine( bool bindData )
        {
            ucPickLine ctlPickLine = (ucPickLine)Page.LoadControl( "~/controls/ucPickLine.ascx" );
            ctlPickLine.LoadReturnReasons();
            ctlPickLine.LoadReturnTypes();
            ctlPickLine.LoadQty();

            plhLines.Controls.Add( ctlPickLine );
        }

        #endregion

        #endregion

        #region Properties

        /// <summary>
        ///  The number of query clauses is stored in view state so that the
        /// interface can be recreated on each page request.
        /// </summary>
        /// <value>The clause count.</value>
        int LineCount
        {
            get
            {
                if ( ViewState["LineCount"] == null )
                    return 5;
                else
                    return (int)ViewState["LineCount"];
            }
            set { ViewState["LineCount"] = value; }
        }
        #endregion
    }
}
